﻿using Farming.Domain;
using Farming.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Farming.Repositories
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, new()
    {
        private readonly FarmingDbContext db;

        public Repository(FarmingDbContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 单条添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> InsertAsync(TEntity entity)
        {
            await db.Set<TEntity>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public virtual async Task<int> InsertAsync(List<TEntity> entities)
        {
            await db.Set<TEntity>().AddRangeAsync(entities);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public virtual async Task<int> DeleteAsync(int Id)
        {
            var entity = await db.Set<TEntity>().FindAsync(Id);
            db.Set<TEntity>().Remove(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 根据条件批量删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public virtual async Task<int> DeleteAsync(Expression<Func<TEntity, bool>> expression)
        {
            var entities = await db.Set<TEntity>().Where(expression).ToListAsync();
            db.Set<TEntity>().RemoveRange(entities);
            return await db.SaveChangesAsync();
        }
    }
}
